package com.bw.controller;

import com.bw.common.MenuTree;
import com.bw.common.Result;
import com.bw.entity.LoginUser;
import com.bw.entity.SysMenu;
import com.bw.entity.UserMenu;
import com.bw.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class MenuController {

    @Autowired
    SysMenuMapper sysMenuMapper;

    @RequestMapping("/getMenuList")
    public Result getMenuList(){
        List<UserMenu> menuList = sysMenuMapper.listAll();

        List<UserMenu> menuTree = MenuTree.makeMenuTree(menuList,0l);

        return Result.ok(menuTree);
    }
    @RequestMapping("/addMenu")
    public Result addMenu(@RequestBody SysMenu sysMenu){
        sysMenu.setCreateTime(new Date());
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysMenu.setCreateBy(principal.getUsername());

        sysMenuMapper.insert(sysMenu);

        return Result.ok("success");
    }
    @RequestMapping("/updateMenu")
    public Result updateMenu(@RequestBody SysMenu sysMenu){
        sysMenu.setUpdateTime(new Date());
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysMenu.setUpdateBy(principal.getUsername());
        sysMenuMapper.updateById(sysMenu);
        return Result.ok("success");
    }
    @RequestMapping("/deleteMenu/{ids}")
    public Result deleteMenu(@PathVariable String ids){
        sysMenuMapper.deleteByMenuId(ids);
        return Result.ok("menuTree");
    }
}
